3 * Preparation for the final page rendering.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Logger\LoggerFactory
;
26 * This class should be covered by a general architecture document which does
27 * not exist as of January 2011. This is one of the Core classes and should
28 * be read at least once by any new developers.
30 * This class is used to prepare the final rendering. A skin is then
31 * applied to the output parameters (links, javascript, html, categories ...).
33 * @todo FIXME: Another class handles sending the whole page to the client.
35 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
40 class OutputPage
extends ContextSource
{
41 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
42 protected $mMetatags = array();
45 protected $mLinktags = array();
48 protected $mCanonicalUrl = false;
51 * @var array Additional stylesheets. Looks like this is for extensions.
52 * Might be replaced by resource loader.
54 protected $mExtStyles = array();
57 * @var string Should be private - has getter and setter. Contains
59 public $mPagetitle = '';
62 * @var string Contains all of the "<body>" content. Should be private we
63 * got set/get accessors and the append() method.
65 public $mBodytext = '';
68 * Holds the debug lines that will be output as comments in page source if
69 * $wgDebugComments is enabled. See also $wgShowDebug.
70 * @deprecated since 1.20; use MWDebug class instead.
72 public $mDebugtext = '';
74 /** @var string Stores contents of "<title>" tag */
75 private $mHTMLtitle = '';
78 * @var bool Is the displayed content related to the source of the
79 * corresponding wiki article.
81 private $mIsarticle = false;
83 /** @var bool Stores "article flag" toggle. */
84 private $mIsArticleRelated = true;
87 * @var bool We have to set isPrintable(). Some pages should
88 * never be printed (ex: redirections).
90 private $mPrintable = false;
93 * @var array Contains the page subtitle. Special pages usually have some
94 * links here. Don't confuse with site subtitle added by skins.
96 private $mSubtitle = array();
99 public $mRedirect = '';
102 protected $mStatusCode;
105 * @var string Variable mLastModified and mEtag are used for sending cache control.
106 * The whole caching system should probably be moved into its own class.
108 protected $mLastModified = '';
111 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
112 * as a unique identifier for the content. It is later used by the client
113 * to compare its cached version with the server version. Client sends
114 * headers If-Match and If-None-Match containing its locally cached ETAG value.
116 * To get more information, you will have to look at HTTP/1.1 protocol which
117 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
119 private $mETag = false;
122 protected $mCategoryLinks = array();
125 protected $mCategories = array();
128 protected $mIndicators = array();
130 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
131 private $mLanguageLinks = array();
134 * Used for JavaScript (pre resource loader)
135 * @todo We should split JS / CSS.
136 * mScripts content is inserted as is in "<head>" by Skin. This might
137 * contain either a link to a stylesheet or inline CSS.
139 private $mScripts = '';
141 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
142 protected $mInlineStyles = '';
145 private $mLinkColours;
148 * @var string Used by skin template.
149 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
151 public $mPageLinkTitle = '';
153 /** @var array Array of elements in "<head>". Parser might add its own headers! */
154 protected $mHeadItems = array();
156 // @todo FIXME: Next 5 variables probably come from the resource loader
159 protected $mModules = array();
162 protected $mModuleScripts = array();
165 protected $mModuleStyles = array();
167 /** @var ResourceLoader */
168 protected $mResourceLoader;
171 protected $mJsConfigVars = array();
174 protected $mTemplateIds = array();
177 protected $mImageTimeKeys = array();
180 public $mRedirectCode = '';
182 protected $mFeedLinksAppendQuery = null;
185 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
186 * @see ResourceLoaderModule::$origin
187 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
189 protected $mAllowedModules = array(
190 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
193 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
194 protected $mDoNothing = false;
199 protected $mContainsNewMagic = 0;
202 * lazy initialised, use parserOptions()
205 protected $mParserOptions = null;
208 * Handles the Atom / RSS links.
209 * We probably only support Atom in 2011.
210 * @see $wgAdvertisedFeedTypes
212 private $mFeedLinks = array();
214 // Gwicke work on squid caching? Roughly from 2003.
215 protected $mEnableClientCache = true;
217 /** @var bool Flag if output should only contain the body of the article. */
218 private $mArticleBodyOnly = false;
221 protected $mNewSectionLink = false;
224 protected $mHideNewSectionLink = false;
227 * @var bool Comes from the parser. This was probably made to load CSS/JS
228 * only if we had "<gallery>". Used directly in CategoryPage.php.
229 * Looks like resource loader can replace this.
231 public $mNoGallery = false;
234 private $mPageTitleActionText = '';
237 private $mParseWarnings = array();
239 /** @var int Cache stuff. Looks like mEnableClientCache */
240 protected $mSquidMaxage = 0;
243 * @var bool Controls if anti-clickjacking / frame-breaking headers will
244 * be sent. This should be done for pages where edit actions are possible.
245 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
247 protected $mPreventClickjacking = true;
249 /** @var int To include the variable {{REVISIONID}} */
250 private $mRevisionId = null;
253 private $mRevisionTimestamp = null;
256 protected $mFileVersion = null;
259 * @var array An array of stylesheet filenames (relative from skins path),
260 * with options for CSS media, IE conditions, and RTL/LTR direction.
261 * For internal use; add settings in the skin via $this->addStyle()
263 * Style again! This seems like a code duplication since we already have
264 * mStyles. This is what makes Open Source amazing.
266 protected $styles = array();
269 * Whether jQuery is already handled.
271 protected $mJQueryDone = false;
273 private $mIndexPolicy = 'index';
274 private $mFollowPolicy = 'follow';
275 private $mVaryHeader = array(
276 'Accept-Encoding' => array( 'list-contains=gzip' ),
280 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
285 private $mRedirectedFrom = null;
288 * Additional key => value data
290 private $mProperties = array();
293 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
295 private $mTarget = null;
298 * @var bool Whether parser output should contain table of contents
300 private $mEnableTOC = true;
303 * @var bool Whether parser output should contain section edit links
305 private $mEnableSectionEditLinks = true;
308 * Constructor for OutputPage. This should not be called directly.
309 * Instead a new RequestContext should be created and it will implicitly create
310 * a OutputPage tied to that context.
311 * @param IContextSource|null $context
313 function __construct( IContextSource
$context = null ) {
314 if ( $context === null ) {
315 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
316 wfDeprecated( __METHOD__
, '1.18' );
318 $this->setContext( $context );
323 * Redirect to $url rather than displaying the normal page
325 * @param string $url URL
326 * @param string $responsecode HTTP status code
328 public function redirect( $url, $responsecode = '302' ) {
329 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
330 $this->mRedirect
= str_replace( "\n", '', $url );
331 $this->mRedirectCode
= $responsecode;
335 * Get the URL to redirect to, or an empty string if not redirect URL set
339 public function getRedirect() {
340 return $this->mRedirect
;
344 * Set the HTTP status code to send with the output.
346 * @param int $statusCode
348 public function setStatusCode( $statusCode ) {
349 $this->mStatusCode
= $statusCode;
353 * Add a new "<meta>" tag
354 * To add an http-equiv meta tag, precede the name with "http:"
356 * @param string $name Tag name
357 * @param string $val Tag value
359 function addMeta( $name, $val ) {
360 array_push( $this->mMetatags
, array( $name, $val ) );
364 * Returns the current <meta> tags
369 public function getMetaTags() {
370 return $this->mMetatags
;
374 * Add a new \<link\> tag to the page header.
376 * Note: use setCanonicalUrl() for rel=canonical.
378 * @param array $linkarr Associative array of attributes.
380 function addLink( array $linkarr ) {
381 array_push( $this->mLinktags
, $linkarr );
385 * Returns the current <link> tags
390 public function getLinkTags() {
391 return $this->mLinktags
;
395 * Add a new \<link\> with "rel" attribute set to "meta"
397 * @param array $linkarr Associative array mapping attribute names to their
398 * values, both keys and values will be escaped, and the
399 * "rel" attribute will be automatically added
401 function addMetadataLink( array $linkarr ) {
402 $linkarr['rel'] = $this->getMetadataAttribute();
403 $this->addLink( $linkarr );
407 * Set the URL to be used for the <link rel=canonical>. This should be used
408 * in preference to addLink(), to avoid duplicate link tags.
411 function setCanonicalUrl( $url ) {
412 $this->mCanonicalUrl
= $url;
416 * Returns the URL to be used for the <link rel=canonical> if
420 * @return bool|string
422 public function getCanonicalUrl() {
423 return $this->mCanonicalUrl
;
427 * Get the value of the "rel" attribute for metadata links
431 public function getMetadataAttribute() {
432 # note: buggy CC software only reads first "meta" link
433 static $haveMeta = false;
435 return 'alternate meta';
443 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
445 * @param string $script Raw HTML
447 function addScript( $script ) {
448 $this->mScripts
.= $script . "\n";
452 * Register and add a stylesheet from an extension directory.
454 * @param string $url Path to sheet. Provide either a full url (beginning
455 * with 'http', etc) or a relative path from the document root
456 * (beginning with '/'). Otherwise it behaves identically to
457 * addStyle() and draws from the /skins folder.
459 public function addExtensionStyle( $url ) {
460 array_push( $this->mExtStyles
, $url );
464 * Get all styles added by extensions
468 function getExtStyle() {
469 return $this->mExtStyles
;
473 * Add a JavaScript file out of skins/common, or a given relative path.
475 * @param string $file Filename in skins/common or complete on-server path
477 * @param string $version Style version of the file. Defaults to $wgStyleVersion
479 public function addScriptFile( $file, $version = null ) {
480 // See if $file parameter is an absolute URL or begins with a slash
481 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
484 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
486 if ( is_null( $version ) ) {
487 $version = $this->getConfig()->get( 'StyleVersion' );
489 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
493 * Add a self-contained script tag with the given contents
495 * @param string $script JavaScript text, no "<script>" tags
497 public function addInlineScript( $script ) {
498 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
502 * Get all registered JS and CSS tags for the header.
505 * @deprecated since 1.24 Use OutputPage::headElement to build the full header.
507 function getScript() {
508 wfDeprecated( __METHOD__
, '1.24' );
509 return $this->mScripts
. $this->getHeadItems();
513 * Filter an array of modules to remove insufficiently trustworthy members, and modules
514 * which are no longer registered (eg a page is cached before an extension is disabled)
515 * @param array $modules
516 * @param string|null $position If not null, only return modules with this position
517 * @param string $type
520 protected function filterModules( array $modules, $position = null,
521 $type = ResourceLoaderModule
::TYPE_COMBINED
523 $resourceLoader = $this->getResourceLoader();
524 $filteredModules = array();
525 foreach ( $modules as $val ) {
526 $module = $resourceLoader->getModule( $val );
527 if ( $module instanceof ResourceLoaderModule
528 && $module->getOrigin() <= $this->getAllowedModules( $type )
529 && ( is_null( $position ) ||
$module->getPosition() == $position )
530 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
532 $filteredModules[] = $val;
535 return $filteredModules;
539 * Get the list of modules to include on this page
541 * @param bool $filter Whether to filter out insufficiently trustworthy modules
542 * @param string|null $position If not null, only return modules with this position
543 * @param string $param
544 * @return array Array of module names
546 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
547 $modules = array_values( array_unique( $this->$param ) );
549 ?
$this->filterModules( $modules, $position )
554 * Add one or more modules recognized by the resource loader. Modules added
555 * through this function will be loaded by the resource loader when the
558 * @param string|array $modules Module name (string) or array of module names
560 public function addModules( $modules ) {
561 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
565 * Get the list of module JS to include on this page
567 * @param bool $filter
568 * @param string|null $position
570 * @return array Array of module names
572 public function getModuleScripts( $filter = false, $position = null ) {
573 return $this->getModules( $filter, $position, 'mModuleScripts' );
577 * Add only JS of one or more modules recognized by the resource loader. Module
578 * scripts added through this function will be loaded by the resource loader when
581 * @param string|array $modules Module name (string) or array of module names
583 public function addModuleScripts( $modules ) {
584 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
588 * Get the list of module CSS to include on this page
590 * @param bool $filter
591 * @param string|null $position
593 * @return array Array of module names
595 public function getModuleStyles( $filter = false, $position = null ) {
597 $resourceLoader = $this->getResourceLoader();
599 foreach ( $this->mModuleStyles
as $val ) {
600 $module = $resourceLoader->getModule( $val );
602 if ( $module instanceof ResourceLoaderModule
&& $module->isPositionDefault() ) {
603 $warning = __METHOD__
. ': style module should define its position explicitly: ' . $val . ' ' . get_class( $module );
604 wfDebugLog( 'resourceloader', $warning );
605 wfLogWarning( $warning );
609 return $this->getModules( $filter, $position, 'mModuleStyles' );
613 * Add only CSS of one or more modules recognized by the resource loader.
615 * Module styles added through this function will be added using standard link CSS
616 * tags, rather than as a combined Javascript and CSS package. Thus, they will
617 * load when JavaScript is disabled (unless CSS also happens to be disabled).
619 * @param string|array $modules Module name (string) or array of module names
621 public function addModuleStyles( $modules ) {
622 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
626 * Get the list of module messages to include on this page
628 * @deprecated since 1.26 Obsolete
629 * @param bool $filter
630 * @param string|null $position
631 * @return array Array of module names
633 public function getModuleMessages( $filter = false, $position = null ) {
634 wfDeprecated( __METHOD__
, '1.26' );
639 * Load messages of one or more ResourceLoader modules.
641 * @deprecated since 1.26 Use addModules() instead
642 * @param string|array $modules Module name (string) or array of module names
644 public function addModuleMessages( $modules ) {
645 wfDeprecated( __METHOD__
, '1.26' );
649 * @return null|string ResourceLoader target
651 public function getTarget() {
652 return $this->mTarget
;
656 * Sets ResourceLoader target for load.php links. If null, will be omitted
658 * @param string|null $target
660 public function setTarget( $target ) {
661 $this->mTarget
= $target;
665 * Get an array of head items
669 function getHeadItemsArray() {
670 return $this->mHeadItems
;
674 * Get all header items in a string
677 * @deprecated since 1.24 Use OutputPage::headElement or
678 * if absolutely necessary use OutputPage::getHeadItemsArray
680 function getHeadItems() {
681 wfDeprecated( __METHOD__
, '1.24' );
683 foreach ( $this->mHeadItems
as $item ) {
690 * Add or replace an header item to the output
692 * @param string $name Item name
693 * @param string $value Raw HTML
695 public function addHeadItem( $name, $value ) {
696 $this->mHeadItems
[$name] = $value;
700 * Check if the header item $name is already set
702 * @param string $name Item name
705 public function hasHeadItem( $name ) {
706 return isset( $this->mHeadItems
[$name] );
710 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
712 * @param string $tag Value of "ETag" header
714 function setETag( $tag ) {
719 * Set whether the output should only contain the body of the article,
720 * without any skin, sidebar, etc.
721 * Used e.g. when calling with "action=render".
723 * @param bool $only Whether to output only the body of the article
725 public function setArticleBodyOnly( $only ) {
726 $this->mArticleBodyOnly
= $only;
730 * Return whether the output will contain only the body of the article
734 public function getArticleBodyOnly() {
735 return $this->mArticleBodyOnly
;
739 * Set an additional output property
742 * @param string $name
743 * @param mixed $value
745 public function setProperty( $name, $value ) {
746 $this->mProperties
[$name] = $value;
750 * Get an additional output property
753 * @param string $name
754 * @return mixed Property value or null if not found
756 public function getProperty( $name ) {
757 if ( isset( $this->mProperties
[$name] ) ) {
758 return $this->mProperties
[$name];
765 * checkLastModified tells the client to use the client-cached page if
766 * possible. If successful, the OutputPage is disabled so that
767 * any future call to OutputPage->output() have no effect.
769 * Side effect: sets mLastModified for Last-Modified header
771 * @param string $timestamp
773 * @return bool True if cache-ok headers was sent.
775 public function checkLastModified( $timestamp ) {
776 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
777 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
780 $config = $this->getConfig();
781 if ( !$config->get( 'CachePages' ) ) {
782 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
786 $timestamp = wfTimestamp( TS_MW
, $timestamp );
787 $modifiedTimes = array(
788 'page' => $timestamp,
789 'user' => $this->getUser()->getTouched(),
790 'epoch' => $config->get( 'CacheEpoch' )
792 if ( $config->get( 'UseSquid' ) ) {
793 // bug 44570: the core page itself may not change, but resources might
794 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
796 Hooks
::run( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
798 $maxModified = max( $modifiedTimes );
799 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
801 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
802 if ( $clientHeader === false ) {
803 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", 'log' );
807 # IE sends sizes after the date like this:
808 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
809 # this breaks strtotime().
810 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
812 wfSuppressWarnings(); // E_STRICT system time bitching
813 $clientHeaderTime = strtotime( $clientHeader );
815 if ( !$clientHeaderTime ) {
817 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
820 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
824 foreach ( $modifiedTimes as $name => $value ) {
825 if ( $info !== '' ) {
828 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
831 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
832 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", 'log' );
833 wfDebug( __METHOD__
. ": effective Last-Modified: " .
834 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", 'log' );
835 if ( $clientHeaderTime < $maxModified ) {
836 wfDebug( __METHOD__
. ": STALE, $info\n", 'log' );
841 # Give a 304 Not Modified response code and disable body output
842 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", 'log' );
843 ini_set( 'zlib.output_compression', 0 );
844 $this->getRequest()->response()->statusHeader( 304 );
845 $this->sendCacheControl();
848 // Don't output a compressed blob when using ob_gzhandler;
849 // it's technically against HTTP spec and seems to confuse
850 // Firefox when the response gets split over two packets.
851 wfClearOutputBuffers();
857 * Override the last modified timestamp
859 * @param string $timestamp New timestamp, in a format readable by
862 public function setLastModified( $timestamp ) {
863 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
867 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
869 * @param string $policy The literal string to output as the contents of
870 * the meta tag. Will be parsed according to the spec and output in
874 public function setRobotPolicy( $policy ) {
875 $policy = Article
::formatRobotPolicy( $policy );
877 if ( isset( $policy['index'] ) ) {
878 $this->setIndexPolicy( $policy['index'] );
880 if ( isset( $policy['follow'] ) ) {
881 $this->setFollowPolicy( $policy['follow'] );
886 * Set the index policy for the page, but leave the follow policy un-
889 * @param string $policy Either 'index' or 'noindex'.
892 public function setIndexPolicy( $policy ) {
893 $policy = trim( $policy );
894 if ( in_array( $policy, array( 'index', 'noindex' ) ) ) {
895 $this->mIndexPolicy
= $policy;
900 * Set the follow policy for the page, but leave the index policy un-
903 * @param string $policy Either 'follow' or 'nofollow'.
906 public function setFollowPolicy( $policy ) {
907 $policy = trim( $policy );
908 if ( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
909 $this->mFollowPolicy
= $policy;
914 * Set the new value of the "action text", this will be added to the
915 * "HTML title", separated from it with " - ".
917 * @param string $text New value of the "action text"
919 public function setPageTitleActionText( $text ) {
920 $this->mPageTitleActionText
= $text;
924 * Get the value of the "action text"
928 public function getPageTitleActionText() {
929 return $this->mPageTitleActionText
;
933 * "HTML title" means the contents of "<title>".
934 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
936 * @param string|Message $name
938 public function setHTMLTitle( $name ) {
939 if ( $name instanceof Message
) {
940 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
942 $this->mHTMLtitle
= $name;
947 * Return the "HTML title", i.e. the content of the "<title>" tag.
951 public function getHTMLTitle() {
952 return $this->mHTMLtitle
;
956 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
960 public function setRedirectedFrom( $t ) {
961 $this->mRedirectedFrom
= $t;
965 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
966 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
967 * but not bad tags like \<script\>. This function automatically sets
968 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
969 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
970 * good tags like \<i\> will be dropped entirely.
972 * @param string|Message $name
974 public function setPageTitle( $name ) {
975 if ( $name instanceof Message
) {
976 $name = $name->setContext( $this->getContext() )->text();
979 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
980 # but leave "<i>foobar</i>" alone
981 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
982 $this->mPagetitle
= $nameWithTags;
984 # change "<i>foo&bar</i>" to "foo&bar"
986 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
987 ->inContentLanguage()
992 * Return the "page title", i.e. the content of the \<h1\> tag.
996 public function getPageTitle() {
997 return $this->mPagetitle
;
1001 * Set the Title object to use
1005 public function setTitle( Title
$t ) {
1006 $this->getContext()->setTitle( $t );
1010 * Replace the subtitle with $str
1012 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1014 public function setSubtitle( $str ) {
1015 $this->clearSubtitle();
1016 $this->addSubtitle( $str );
1020 * Add $str to the subtitle
1022 * @deprecated since 1.19; use addSubtitle() instead
1023 * @param string|Message $str String or Message to add to the subtitle
1025 public function appendSubtitle( $str ) {
1026 $this->addSubtitle( $str );
1030 * Add $str to the subtitle
1032 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1034 public function addSubtitle( $str ) {
1035 if ( $str instanceof Message
) {
1036 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1038 $this->mSubtitle
[] = $str;
1043 * Build message object for a subtitle containing a backlink to a page
1045 * @param Title $title Title to link to
1046 * @param array $query Array of additional parameters to include in the link
1050 public static function buildBacklinkSubtitle( Title
$title, $query = array() ) {
1051 if ( $title->isRedirect() ) {
1052 $query['redirect'] = 'no';
1054 return wfMessage( 'backlinksubtitle' )
1055 ->rawParams( Linker
::link( $title, null, array(), $query ) );
1059 * Add a subtitle containing a backlink to a page
1061 * @param Title $title Title to link to
1062 * @param array $query Array of additional parameters to include in the link
1064 public function addBacklinkSubtitle( Title
$title, $query = array() ) {
1065 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1069 * Clear the subtitles
1071 public function clearSubtitle() {
1072 $this->mSubtitle
= array();
1080 public function getSubtitle() {
1081 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1085 * Set the page as printable, i.e. it'll be displayed with all
1086 * print styles included
1088 public function setPrintable() {
1089 $this->mPrintable
= true;
1093 * Return whether the page is "printable"
1097 public function isPrintable() {
1098 return $this->mPrintable
;
1102 * Disable output completely, i.e. calling output() will have no effect
1104 public function disable() {
1105 $this->mDoNothing
= true;
1109 * Return whether the output will be completely disabled
1113 public function isDisabled() {
1114 return $this->mDoNothing
;
1118 * Show an "add new section" link?
1122 public function showNewSectionLink() {
1123 return $this->mNewSectionLink
;
1127 * Forcibly hide the new section link?
1131 public function forceHideNewSectionLink() {
1132 return $this->mHideNewSectionLink
;
1136 * Add or remove feed links in the page header
1137 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1138 * for the new version
1139 * @see addFeedLink()
1141 * @param bool $show True: add default feeds, false: remove all feeds
1143 public function setSyndicated( $show = true ) {
1145 $this->setFeedAppendQuery( false );
1147 $this->mFeedLinks
= array();
1152 * Add default feeds to the page header
1153 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1154 * for the new version
1155 * @see addFeedLink()
1157 * @param string $val Query to append to feed links or false to output
1160 public function setFeedAppendQuery( $val ) {
1161 $this->mFeedLinks
= array();
1163 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1164 $query = "feed=$type";
1165 if ( is_string( $val ) ) {
1166 $query .= '&' . $val;
1168 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1173 * Add a feed link to the page header
1175 * @param string $format Feed type, should be a key of $wgFeedClasses
1176 * @param string $href URL
1178 public function addFeedLink( $format, $href ) {
1179 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1180 $this->mFeedLinks
[$format] = $href;
1185 * Should we output feed links for this page?
1188 public function isSyndicated() {
1189 return count( $this->mFeedLinks
) > 0;
1193 * Return URLs for each supported syndication format for this page.
1194 * @return array Associating format keys with URLs
1196 public function getSyndicationLinks() {
1197 return $this->mFeedLinks
;
1201 * Will currently always return null
1205 public function getFeedAppendQuery() {
1206 return $this->mFeedLinksAppendQuery
;
1210 * Set whether the displayed content is related to the source of the
1211 * corresponding article on the wiki
1212 * Setting true will cause the change "article related" toggle to true
1216 public function setArticleFlag( $v ) {
1217 $this->mIsarticle
= $v;
1219 $this->mIsArticleRelated
= $v;
1224 * Return whether the content displayed page is related to the source of
1225 * the corresponding article on the wiki
1229 public function isArticle() {
1230 return $this->mIsarticle
;
1234 * Set whether this page is related an article on the wiki
1235 * Setting false will cause the change of "article flag" toggle to false
1239 public function setArticleRelated( $v ) {
1240 $this->mIsArticleRelated
= $v;
1242 $this->mIsarticle
= false;
1247 * Return whether this page is related an article on the wiki
1251 public function isArticleRelated() {
1252 return $this->mIsArticleRelated
;
1256 * Add new language links
1258 * @param array $newLinkArray Associative array mapping language code to the page
1261 public function addLanguageLinks( array $newLinkArray ) {
1262 $this->mLanguageLinks +
= $newLinkArray;
1266 * Reset the language links and add new language links
1268 * @param array $newLinkArray Associative array mapping language code to the page
1271 public function setLanguageLinks( array $newLinkArray ) {
1272 $this->mLanguageLinks
= $newLinkArray;
1276 * Get the list of language links
1278 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1280 public function getLanguageLinks() {
1281 return $this->mLanguageLinks
;
1285 * Add an array of categories, with names in the keys
1287 * @param array $categories Mapping category name => sort key
1289 public function addCategoryLinks( array $categories ) {
1292 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1296 # Add the links to a LinkBatch
1297 $arr = array( NS_CATEGORY
=> $categories );
1298 $lb = new LinkBatch
;
1299 $lb->setArray( $arr );
1301 # Fetch existence plus the hiddencat property
1302 $dbr = wfGetDB( DB_SLAVE
);
1303 $fields = array( 'page_id', 'page_namespace', 'page_title', 'page_len',
1304 'page_is_redirect', 'page_latest', 'pp_value' );
1306 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
1307 $fields[] = 'page_content_model';
1310 $res = $dbr->select( array( 'page', 'page_props' ),
1312 $lb->constructSet( 'page', $dbr ),
1315 array( 'page_props' => array( 'LEFT JOIN', array(
1316 'pp_propname' => 'hiddencat',
1321 # Add the results to the link cache
1322 $lb->addResultToCache( LinkCache
::singleton(), $res );
1324 # Set all the values to 'normal'.
1325 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1327 # Mark hidden categories
1328 foreach ( $res as $row ) {
1329 if ( isset( $row->pp_value
) ) {
1330 $categories[$row->page_title
] = 'hidden';
1334 # Add the remaining categories to the skin
1336 'OutputPageMakeCategoryLinks',
1337 array( &$this, $categories, &$this->mCategoryLinks
) )
1339 foreach ( $categories as $category => $type ) {
1340 $origcategory = $category;
1341 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1345 $wgContLang->findVariantLink( $category, $title, true );
1346 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1349 $text = $wgContLang->convertHtml( $title->getText() );
1350 $this->mCategories
[] = $title->getText();
1351 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1357 * Reset the category links (but not the category list) and add $categories
1359 * @param array $categories Mapping category name => sort key
1361 public function setCategoryLinks( array $categories ) {
1362 $this->mCategoryLinks
= array();
1363 $this->addCategoryLinks( $categories );
1367 * Get the list of category links, in a 2-D array with the following format:
1368 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1369 * hidden categories) and $link a HTML fragment with a link to the category
1374 public function getCategoryLinks() {
1375 return $this->mCategoryLinks
;
1379 * Get the list of category names this page belongs to
1381 * @return array Array of strings
1383 public function getCategories() {
1384 return $this->mCategories
;
1388 * Add an array of indicators, with their identifiers as array
1389 * keys and HTML contents as values.
1391 * In case of duplicate keys, existing values are overwritten.
1393 * @param array $indicators
1396 public function setIndicators( array $indicators ) {
1397 $this->mIndicators
= $indicators +
$this->mIndicators
;
1398 // Keep ordered by key
1399 ksort( $this->mIndicators
);
1403 * Get the indicators associated with this page.
1405 * The array will be internally ordered by item keys.
1407 * @return array Keys: identifiers, values: HTML contents
1410 public function getIndicators() {
1411 return $this->mIndicators
;
1415 * Adds help link with an icon via page indicators.
1416 * Link target can be overridden by a local message containing a wikilink:
1417 * the message key is: lowercase action or special page name + '-helppage'.
1418 * @param string $to Target MediaWiki.org page title or encoded URL.
1419 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1422 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1423 $this->addModuleStyles( 'mediawiki.helplink' );
1424 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1426 if ( $overrideBaseUrl ) {
1429 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1430 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1433 $link = Html
::rawElement(
1437 'target' => '_blank',
1438 'class' => 'mw-helplink',
1443 $this->setIndicators( array( 'mw-helplink' => $link ) );
1447 * Do not allow scripts which can be modified by wiki users to load on this page;
1448 * only allow scripts bundled with, or generated by, the software.
1449 * Site-wide styles are controlled by a config setting, since they can be
1450 * used to create a custom skin/theme, but not user-specific ones.
1452 * @todo this should be given a more accurate name
1454 public function disallowUserJs() {
1455 $this->reduceAllowedModules(
1456 ResourceLoaderModule
::TYPE_SCRIPTS
,
1457 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1460 // Site-wide styles are controlled by a config setting, see bug 71621
1461 // for background on why. User styles are never allowed.
1462 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1463 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1465 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1467 $this->reduceAllowedModules(
1468 ResourceLoaderModule
::TYPE_STYLES
,
1474 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1475 * @see ResourceLoaderModule::$origin
1476 * @param string $type ResourceLoaderModule TYPE_ constant
1477 * @return int ResourceLoaderModule ORIGIN_ class constant
1479 public function getAllowedModules( $type ) {
1480 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1481 return min( array_values( $this->mAllowedModules
) );
1483 return isset( $this->mAllowedModules
[$type] )
1484 ?
$this->mAllowedModules
[$type]
1485 : ResourceLoaderModule
::ORIGIN_ALL
;
1490 * Set the highest level of CSS/JS untrustworthiness allowed
1492 * @deprecated since 1.24 Raising level of allowed untrusted content is no longer supported.
1493 * Use reduceAllowedModules() instead
1494 * @param string $type ResourceLoaderModule TYPE_ constant
1495 * @param int $level ResourceLoaderModule class constant
1497 public function setAllowedModules( $type, $level ) {
1498 wfDeprecated( __METHOD__
, '1.24' );
1499 $this->reduceAllowedModules( $type, $level );
1503 * Limit the highest level of CSS/JS untrustworthiness allowed.
1505 * If passed the same or a higher level than the current level of untrustworthiness set, the
1506 * level will remain unchanged.
1508 * @param string $type
1509 * @param int $level ResourceLoaderModule class constant
1511 public function reduceAllowedModules( $type, $level ) {
1512 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1516 * Prepend $text to the body HTML
1518 * @param string $text HTML
1520 public function prependHTML( $text ) {
1521 $this->mBodytext
= $text . $this->mBodytext
;
1525 * Append $text to the body HTML
1527 * @param string $text HTML
1529 public function addHTML( $text ) {
1530 $this->mBodytext
.= $text;
1534 * Shortcut for adding an Html::element via addHTML.
1538 * @param string $element
1539 * @param array $attribs
1540 * @param string $contents
1542 public function addElement( $element, array $attribs = array(), $contents = '' ) {
1543 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1547 * Clear the body HTML
1549 public function clearHTML() {
1550 $this->mBodytext
= '';
1556 * @return string HTML
1558 public function getHTML() {
1559 return $this->mBodytext
;
1563 * Get/set the ParserOptions object to use for wikitext parsing
1565 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1566 * current ParserOption object
1567 * @return ParserOptions
1569 public function parserOptions( $options = null ) {
1570 if ( !$this->mParserOptions
) {
1571 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1572 $this->mParserOptions
->setEditSection( false );
1574 return wfSetVar( $this->mParserOptions
, $options );
1578 * Set the revision ID which will be seen by the wiki text parser
1579 * for things such as embedded {{REVISIONID}} variable use.
1581 * @param int|null $revid An positive integer, or null
1582 * @return mixed Previous value
1584 public function setRevisionId( $revid ) {
1585 $val = is_null( $revid ) ?
null : intval( $revid );
1586 return wfSetVar( $this->mRevisionId
, $val );
1590 * Get the displayed revision ID
1594 public function getRevisionId() {
1595 return $this->mRevisionId
;
1599 * Set the timestamp of the revision which will be displayed. This is used
1600 * to avoid a extra DB call in Skin::lastModified().
1602 * @param string|null $timestamp
1603 * @return mixed Previous value
1605 public function setRevisionTimestamp( $timestamp ) {
1606 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1610 * Get the timestamp of displayed revision.
1611 * This will be null if not filled by setRevisionTimestamp().
1613 * @return string|null
1615 public function getRevisionTimestamp() {
1616 return $this->mRevisionTimestamp
;
1620 * Set the displayed file version
1622 * @param File|bool $file
1623 * @return mixed Previous value
1625 public function setFileVersion( $file ) {
1627 if ( $file instanceof File
&& $file->exists() ) {
1628 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1630 return wfSetVar( $this->mFileVersion
, $val, true );
1634 * Get the displayed file version
1636 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1638 public function getFileVersion() {
1639 return $this->mFileVersion
;
1643 * Get the templates used on this page
1645 * @return array (namespace => dbKey => revId)
1648 public function getTemplateIds() {
1649 return $this->mTemplateIds
;
1653 * Get the files used on this page
1655 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1658 public function getFileSearchOptions() {
1659 return $this->mImageTimeKeys
;
1663 * Convert wikitext to HTML and add it to the buffer
1664 * Default assumes that the current page title will be used.
1666 * @param string $text
1667 * @param bool $linestart Is this the start of a line?
1668 * @param bool $interface Is this text in the user interface language?
1669 * @throws MWException
1671 public function addWikiText( $text, $linestart = true, $interface = true ) {
1672 $title = $this->getTitle(); // Work around E_STRICT
1674 throw new MWException( 'Title is null' );
1676 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1680 * Add wikitext with a custom Title object
1682 * @param string $text Wikitext
1683 * @param Title $title
1684 * @param bool $linestart Is this the start of a line?
1686 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1687 $this->addWikiTextTitle( $text, $title, $linestart );
1691 * Add wikitext with a custom Title object and tidy enabled.
1693 * @param string $text Wikitext
1694 * @param Title $title
1695 * @param bool $linestart Is this the start of a line?
1697 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1698 $this->addWikiTextTitle( $text, $title, $linestart, true );
1702 * Add wikitext with tidy enabled
1704 * @param string $text Wikitext
1705 * @param bool $linestart Is this the start of a line?
1707 public function addWikiTextTidy( $text, $linestart = true ) {
1708 $title = $this->getTitle();
1709 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1713 * Add wikitext with a custom Title object
1715 * @param string $text Wikitext
1716 * @param Title $title
1717 * @param bool $linestart Is this the start of a line?
1718 * @param bool $tidy Whether to use tidy
1719 * @param bool $interface Whether it is an interface message
1720 * (for example disables conversion)
1722 public function addWikiTextTitle( $text, Title
$title, $linestart,
1723 $tidy = false, $interface = false
1727 $popts = $this->parserOptions();
1728 $oldTidy = $popts->setTidy( $tidy );
1729 $popts->setInterfaceMessage( (bool)$interface );
1731 $parserOutput = $wgParser->getFreshParser()->parse(
1732 $text, $title, $popts,
1733 $linestart, true, $this->mRevisionId
1736 $popts->setTidy( $oldTidy );
1738 $this->addParserOutput( $parserOutput );
1743 * Add a ParserOutput object, but without Html.
1745 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1746 * @param ParserOutput $parserOutput
1748 public function addParserOutputNoText( $parserOutput ) {
1749 $this->addParserOutputMetadata( $parserOutput );
1753 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1754 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1758 * @param ParserOutput $parserOutput
1760 public function addParserOutputMetadata( $parserOutput ) {
1761 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1762 $this->addCategoryLinks( $parserOutput->getCategories() );
1763 $this->setIndicators( $parserOutput->getIndicators() );
1764 $this->mNewSectionLink
= $parserOutput->getNewSection();
1765 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1767 $this->mParseWarnings
= $parserOutput->getWarnings();
1768 if ( !$parserOutput->isCacheable() ) {
1769 $this->enableClientCache( false );
1771 $this->mNoGallery
= $parserOutput->getNoGallery();
1772 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1773 $this->addModules( $parserOutput->getModules() );
1774 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1775 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1776 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1777 $this->mPreventClickjacking
= $this->mPreventClickjacking
1778 ||
$parserOutput->preventClickjacking();
1780 // Template versioning...
1781 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1782 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1783 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1785 $this->mTemplateIds
[$ns] = $dbks;
1788 // File versioning...
1789 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1790 $this->mImageTimeKeys
[$dbk] = $data;
1793 // Hooks registered in the object
1794 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1795 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1796 list( $hookName, $data ) = $hookInfo;
1797 if ( isset( $parserOutputHooks[$hookName] ) ) {
1798 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1802 // Link flags are ignored for now, but may in the future be
1803 // used to mark individual language links.
1804 $linkFlags = array();
1805 Hooks
::run( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ) );
1806 Hooks
::run( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1810 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1811 * ParserOutput object, without any other metadata.
1814 * @param ParserOutput $parserOutput
1816 public function addParserOutputContent( $parserOutput ) {
1817 $this->addParserOutputText( $parserOutput );
1819 $this->addModules( $parserOutput->getModules() );
1820 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1821 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1823 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1827 * Add the HTML associated with a ParserOutput object, without any metadata.
1830 * @param ParserOutput $parserOutput
1832 public function addParserOutputText( $parserOutput ) {
1833 $text = $parserOutput->getText();
1834 Hooks
::run( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1835 $this->addHTML( $text );
1839 * Add everything from a ParserOutput object.
1841 * @param ParserOutput $parserOutput
1843 function addParserOutput( $parserOutput ) {
1844 $this->addParserOutputMetadata( $parserOutput );
1845 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1847 // Touch section edit links only if not previously disabled
1848 if ( $parserOutput->getEditSectionTokens() ) {
1849 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1852 $this->addParserOutputText( $parserOutput );
1856 * Add the output of a QuickTemplate to the output buffer
1858 * @param QuickTemplate $template
1860 public function addTemplate( &$template ) {
1861 $this->addHTML( $template->getHTML() );
1865 * Parse wikitext and return the HTML.
1867 * @param string $text
1868 * @param bool $linestart Is this the start of a line?
1869 * @param bool $interface Use interface language ($wgLang instead of
1870 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1871 * This also disables LanguageConverter.
1872 * @param Language $language Target language object, will override $interface
1873 * @throws MWException
1874 * @return string HTML
1876 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1879 if ( is_null( $this->getTitle() ) ) {
1880 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1883 $popts = $this->parserOptions();
1885 $popts->setInterfaceMessage( true );
1887 if ( $language !== null ) {
1888 $oldLang = $popts->setTargetLanguage( $language );
1891 $parserOutput = $wgParser->getFreshParser()->parse(
1892 $text, $this->getTitle(), $popts,
1893 $linestart, true, $this->mRevisionId
1897 $popts->setInterfaceMessage( false );
1899 if ( $language !== null ) {
1900 $popts->setTargetLanguage( $oldLang );
1903 return $parserOutput->getText();
1907 * Parse wikitext, strip paragraphs, and return the HTML.
1909 * @param string $text
1910 * @param bool $linestart Is this the start of a line?
1911 * @param bool $interface Use interface language ($wgLang instead of
1912 * $wgContLang) while parsing language sensitive magic
1913 * words like GRAMMAR and PLURAL
1914 * @return string HTML
1916 public function parseInline( $text, $linestart = true, $interface = false ) {
1917 $parsed = $this->parse( $text, $linestart, $interface );
1918 return Parser
::stripOuterParagraph( $parsed );
1922 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1924 * @param int $maxage Maximum cache time on the Squid, in seconds.
1926 public function setSquidMaxage( $maxage ) {
1927 $this->mSquidMaxage
= $maxage;
1931 * Use enableClientCache(false) to force it to send nocache headers
1933 * @param bool $state
1937 public function enableClientCache( $state ) {
1938 return wfSetVar( $this->mEnableClientCache
, $state );
1942 * Get the list of cookies that will influence on the cache
1946 function getCacheVaryCookies() {
1948 if ( $cookies === null ) {
1949 $config = $this->getConfig();
1950 $cookies = array_merge(
1952 $config->get( 'CookiePrefix' ) . 'Token',
1953 $config->get( 'CookiePrefix' ) . 'LoggedOut',
1957 $config->get( 'CacheVaryCookies' )
1959 Hooks
::run( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1965 * Check if the request has a cache-varying cookie header
1966 * If it does, it's very important that we don't allow public caching
1970 function haveCacheVaryCookies() {
1971 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1972 if ( $cookieHeader === false ) {
1975 $cvCookies = $this->getCacheVaryCookies();
1976 foreach ( $cvCookies as $cookieName ) {
1977 # Check for a simple string match, like the way squid does it
1978 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1979 wfDebug( __METHOD__
. ": found $cookieName\n" );
1983 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1988 * Add an HTTP header that will influence on the cache
1990 * @param string $header Header name
1991 * @param array|null $option
1992 * @todo FIXME: Document the $option parameter; it appears to be for
1993 * X-Vary-Options but what format is acceptable?
1995 public function addVaryHeader( $header, $option = null ) {
1996 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1997 $this->mVaryHeader
[$header] = (array)$option;
1998 } elseif ( is_array( $option ) ) {
1999 if ( is_array( $this->mVaryHeader
[$header] ) ) {
2000 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
2002 $this->mVaryHeader
[$header] = $option;
2005 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
2009 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2010 * such as Accept-Encoding or Cookie
2014 public function getVaryHeader() {
2015 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) );
2019 * Get a complete X-Vary-Options header
2023 public function getXVO() {
2024 $cvCookies = $this->getCacheVaryCookies();
2026 $cookiesOption = array();
2027 foreach ( $cvCookies as $cookieName ) {
2028 $cookiesOption[] = 'string-contains=' . $cookieName;
2030 $this->addVaryHeader( 'Cookie', $cookiesOption );
2033 foreach ( $this->mVaryHeader
as $header => $option ) {
2034 $newheader = $header;
2035 if ( is_array( $option ) && count( $option ) > 0 ) {
2036 $newheader .= ';' . implode( ';', $option );
2038 $headers[] = $newheader;
2040 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
2046 * bug 21672: Add Accept-Language to Vary and XVO headers
2047 * if there's no 'variant' parameter existed in GET.
2050 * /w/index.php?title=Main_page should always be served; but
2051 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2053 function addAcceptLanguage() {
2054 $title = $this->getTitle();
2055 if ( !$title instanceof Title
) {
2059 $lang = $title->getPageLanguage();
2060 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2061 $variants = $lang->getVariants();
2062 $aloption = array();
2063 foreach ( $variants as $variant ) {
2064 if ( $variant === $lang->getCode() ) {
2067 $aloption[] = 'string-contains=' . $variant;
2069 // IE and some other browsers use BCP 47 standards in
2070 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2071 // We should handle these too.
2072 $variantBCP47 = wfBCP47( $variant );
2073 if ( $variantBCP47 !== $variant ) {
2074 $aloption[] = 'string-contains=' . $variantBCP47;
2078 $this->addVaryHeader( 'Accept-Language', $aloption );
2083 * Set a flag which will cause an X-Frame-Options header appropriate for
2084 * edit pages to be sent. The header value is controlled by
2085 * $wgEditPageFrameOptions.
2087 * This is the default for special pages. If you display a CSRF-protected
2088 * form on an ordinary view page, then you need to call this function.
2090 * @param bool $enable
2092 public function preventClickjacking( $enable = true ) {
2093 $this->mPreventClickjacking
= $enable;
2097 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2098 * This can be called from pages which do not contain any CSRF-protected
2101 public function allowClickjacking() {
2102 $this->mPreventClickjacking
= false;
2106 * Get the prevent-clickjacking flag
2111 public function getPreventClickjacking() {
2112 return $this->mPreventClickjacking
;
2116 * Get the X-Frame-Options header value (without the name part), or false
2117 * if there isn't one. This is used by Skin to determine whether to enable
2118 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2122 public function getFrameOptions() {
2123 $config = $this->getConfig();
2124 if ( $config->get( 'BreakFrames' ) ) {
2126 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2127 return $config->get( 'EditPageFrameOptions' );
2133 * Send cache control HTTP headers
2135 public function sendCacheControl() {
2136 $response = $this->getRequest()->response();
2137 $config = $this->getConfig();
2138 if ( $config->get( 'UseETag' ) && $this->mETag
) {
2139 $response->header( "ETag: $this->mETag" );
2142 $this->addVaryHeader( 'Cookie' );
2143 $this->addAcceptLanguage();
2145 # don't serve compressed data to clients who can't handle it
2146 # maintain different caches for logged-in users and non-logged in ones
2147 $response->header( $this->getVaryHeader() );
2149 if ( $config->get( 'UseXVO' ) ) {
2150 # Add an X-Vary-Options header for Squid with Wikimedia patches
2151 $response->header( $this->getXVO() );
2154 if ( $this->mEnableClientCache
) {
2156 $config->get( 'UseSquid' ) && session_id() == '' && !$this->isPrintable() &&
2157 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
2159 if ( $config->get( 'UseESI' ) ) {
2160 # We'll purge the proxy cache explicitly, but require end user agents
2161 # to revalidate against the proxy on each visit.
2162 # Surrogate-Control controls our Squid, Cache-Control downstream caches
2163 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
2164 # start with a shorter timeout for initial testing
2165 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2166 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2167 . '+' . $this->mSquidMaxage
. ', content="ESI/1.0"' );
2168 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2170 # We'll purge the proxy cache for anons explicitly, but require end user agents
2171 # to revalidate against the proxy on each visit.
2172 # IMPORTANT! The Squid needs to replace the Cache-Control header with
2173 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2174 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", 'log' );
2175 # start with a shorter timeout for initial testing
2176 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2177 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
2178 . ', must-revalidate, max-age=0' );
2181 # We do want clients to cache if they can, but they *must* check for updates
2182 # on revisiting the page.
2183 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", 'log' );
2184 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2185 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2187 if ( $this->mLastModified
) {
2188 $response->header( "Last-Modified: {$this->mLastModified}" );
2191 wfDebug( __METHOD__
. ": no caching **\n", 'log' );
2193 # In general, the absence of a last modified header should be enough to prevent
2194 # the client from using its cache. We send a few other things just to make sure.
2195 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2196 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2197 $response->header( 'Pragma: no-cache' );
2202 * Finally, all the text has been munged and accumulated into
2203 * the object, let's actually output it:
2205 public function output() {
2206 if ( $this->mDoNothing
) {
2210 $response = $this->getRequest()->response();
2211 $config = $this->getConfig();
2213 if ( $this->mRedirect
!= '' ) {
2214 # Standards require redirect URLs to be absolute
2215 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2217 $redirect = $this->mRedirect
;
2218 $code = $this->mRedirectCode
;
2220 if ( Hooks
::run( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2221 if ( $code == '301' ||
$code == '303' ) {
2222 if ( !$config->get( 'DebugRedirects' ) ) {
2223 $response->statusHeader( $code );
2225 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2227 if ( $config->get( 'VaryOnXFP' ) ) {
2228 $this->addVaryHeader( 'X-Forwarded-Proto' );
2230 $this->sendCacheControl();
2232 $response->header( "Content-Type: text/html; charset=utf-8" );
2233 if ( $config->get( 'DebugRedirects' ) ) {
2234 $url = htmlspecialchars( $redirect );
2235 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2236 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2237 print "</body>\n</html>\n";
2239 $response->header( 'Location: ' . $redirect );
2244 } elseif ( $this->mStatusCode
) {
2245 $response->statusHeader( $this->mStatusCode
);
2248 # Buffer output; final headers may depend on later processing
2251 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2252 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2254 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2255 // jQuery etc. can work correctly.
2256 $response->header( 'X-UA-Compatible: IE=Edge' );
2258 // Prevent framing, if requested
2259 $frameOptions = $this->getFrameOptions();
2260 if ( $frameOptions ) {
2261 $response->header( "X-Frame-Options: $frameOptions" );
2264 if ( $this->mArticleBodyOnly
) {
2265 echo $this->mBodytext
;
2268 $sk = $this->getSkin();
2269 // add skin specific modules
2270 $modules = $sk->getDefaultModules();
2272 // enforce various default modules for all skins
2273 $coreModules = array(
2274 // keep this list as small as possible
2275 'mediawiki.page.startup',
2279 // Support for high-density display images if enabled
2280 if ( $config->get( 'ResponsiveImages' ) ) {
2281 $coreModules[] = 'mediawiki.hidpi';
2284 $this->addModules( $coreModules );
2285 foreach ( $modules as $group ) {
2286 $this->addModules( $group );
2288 MWDebug
::addModules( $this );
2290 // Hook that allows last minute changes to the output page, e.g.
2291 // adding of CSS or Javascript by extensions.
2292 Hooks
::run( 'BeforePageDisplay', array( &$this, &$sk ) );
2297 // This hook allows last minute changes to final overall output by modifying output buffer
2298 Hooks
::run( 'AfterFinalPageOutput', array( $this ) );
2300 $this->sendCacheControl();
2307 * Actually output something with print.
2309 * @param string $ins The string to output
2310 * @deprecated since 1.22 Use echo yourself.
2312 public function out( $ins ) {
2313 wfDeprecated( __METHOD__
, '1.22' );
2318 * Produce a "user is blocked" page.
2319 * @deprecated since 1.18
2321 function blockedPage() {
2322 throw new UserBlockedError( $this->getUser()->mBlock
);
2326 * Prepare this object to display an error page; disable caching and
2327 * indexing, clear the current text and redirect, set the page's title
2328 * and optionally an custom HTML title (content of the "<title>" tag).
2330 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2331 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2332 * optional, if not passed the "<title>" attribute will be
2333 * based on $pageTitle
2335 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2336 $this->setPageTitle( $pageTitle );
2337 if ( $htmlTitle !== false ) {
2338 $this->setHTMLTitle( $htmlTitle );
2340 $this->setRobotPolicy( 'noindex,nofollow' );
2341 $this->setArticleRelated( false );
2342 $this->enableClientCache( false );
2343 $this->mRedirect
= '';
2344 $this->clearSubtitle();
2349 * Output a standard error page
2351 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2352 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2353 * showErrorPage( 'titlemsg', $messageObject );
2354 * showErrorPage( $titleMessageObject, $messageObject );
2356 * @param string|Message $title Message key (string) for page title, or a Message object
2357 * @param string|Message $msg Message key (string) for page text, or a Message object
2358 * @param array $params Message parameters; ignored if $msg is a Message object
2360 public function showErrorPage( $title, $msg, $params = array() ) {
2361 if ( !$title instanceof Message
) {
2362 $title = $this->msg( $title );
2365 $this->prepareErrorPage( $title );
2367 if ( $msg instanceof Message
) {
2368 if ( $params !== array() ) {
2369 trigger_error( 'Argument ignored: $params. The message parameters argument '
2370 . 'is discarded when the $msg argument is a Message object instead of '
2371 . 'a string.', E_USER_NOTICE
);
2373 $this->addHTML( $msg->parseAsBlock() );
2375 $this->addWikiMsgArray( $msg, $params );
2378 $this->returnToMain();
2382 * Output a standard permission error page
2384 * @param array $errors Error message keys
2385 * @param string $action Action that was denied or null if unknown
2387 public function showPermissionsErrorPage( array $errors, $action = null ) {
2388 // For some action (read, edit, create and upload), display a "login to do this action"
2389 // error if all of the following conditions are met:
2390 // 1. the user is not logged in
2391 // 2. the only error is insufficient permissions (i.e. no block or something else)
2392 // 3. the error can be avoided simply by logging in
2393 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2394 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2395 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2396 && ( User
::groupHasPermission( 'user', $action )
2397 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2399 $displayReturnto = null;
2401 # Due to bug 32276, if a user does not have read permissions,
2402 # $this->getTitle() will just give Special:Badtitle, which is
2403 # not especially useful as a returnto parameter. Use the title
2404 # from the request instead, if there was one.
2405 $request = $this->getRequest();
2406 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2407 if ( $action == 'edit' ) {
2408 $msg = 'whitelistedittext';
2409 $displayReturnto = $returnto;
2410 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2411 $msg = 'nocreatetext';
2412 } elseif ( $action == 'upload' ) {
2413 $msg = 'uploadnologintext';
2415 $msg = 'loginreqpagetext';
2416 $displayReturnto = Title
::newMainPage();
2422 $query['returnto'] = $returnto->getPrefixedText();
2424 if ( !$request->wasPosted() ) {
2425 $returntoquery = $request->getValues();
2426 unset( $returntoquery['title'] );
2427 unset( $returntoquery['returnto'] );
2428 unset( $returntoquery['returntoquery'] );
2429 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2432 $loginLink = Linker
::linkKnown(
2433 SpecialPage
::getTitleFor( 'Userlogin' ),
2434 $this->msg( 'loginreqlink' )->escaped(),
2439 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2440 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2442 # Don't return to a page the user can't read otherwise
2443 # we'll end up in a pointless loop
2444 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2445 $this->returnToMain( null, $displayReturnto );
2448 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2449 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2454 * Display an error page indicating that a given version of MediaWiki is
2455 * required to use it
2457 * @param mixed $version The version of MediaWiki needed to use the page
2459 public function versionRequired( $version ) {
2460 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2462 $this->addWikiMsg( 'versionrequiredtext', $version );
2463 $this->returnToMain();
2467 * Display an error page noting that a given permission bit is required.
2468 * @deprecated since 1.18, just throw the exception directly
2469 * @param string $permission Key required
2470 * @throws PermissionsError
2472 public function permissionRequired( $permission ) {
2473 throw new PermissionsError( $permission );
2477 * Produce the stock "please login to use the wiki" page
2479 * @deprecated since 1.19; throw the exception directly
2481 public function loginToUse() {
2482 throw new PermissionsError( 'read' );
2486 * Format a list of error messages
2488 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2489 * @param string $action Action that was denied or null if unknown
2490 * @return string The wikitext error-messages, formatted into a list.
2492 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2493 if ( $action == null ) {
2494 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2496 $action_desc = $this->msg( "action-$action" )->plain();
2498 'permissionserrorstext-withaction',
2501 )->plain() . "\n\n";
2504 if ( count( $errors ) > 1 ) {
2505 $text .= '<ul class="permissions-errors">' . "\n";
2507 foreach ( $errors as $error ) {
2509 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2514 $text .= "<div class=\"permissions-errors\">\n" .
2515 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2523 * Display a page stating that the Wiki is in read-only mode.
2524 * Should only be called after wfReadOnly() has returned true.
2526 * Historically, this function was used to show the source of the page that the user
2527 * was trying to edit and _also_ permissions error messages. The relevant code was
2528 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2530 * @deprecated since 1.25; throw the exception directly
2531 * @throws ReadOnlyError
2533 public function readOnlyPage() {
2534 if ( func_num_args() > 0 ) {
2535 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2538 throw new ReadOnlyError
;
2542 * Turn off regular page output and return an error response
2543 * for when rate limiting has triggered.
2545 * @deprecated since 1.25; throw the exception directly
2547 public function rateLimited() {
2548 wfDeprecated( __METHOD__
, '1.25' );
2549 throw new ThrottledError
;
2553 * Show a warning about slave lag
2555 * If the lag is higher than $wgSlaveLagCritical seconds,
2556 * then the warning is a bit more obvious. If the lag is
2557 * lower than $wgSlaveLagWarning, then no warning is shown.
2559 * @param int $lag Slave lag
2561 public function showLagWarning( $lag ) {
2562 $config = $this->getConfig();
2563 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2564 $message = $lag < $config->get( 'SlaveLagCritical' )
2567 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2568 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2572 public function showFatalError( $message ) {
2573 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2575 $this->addHTML( $message );
2578 public function showUnexpectedValueError( $name, $val ) {
2579 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2582 public function showFileCopyError( $old, $new ) {
2583 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2586 public function showFileRenameError( $old, $new ) {
2587 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2590 public function showFileDeleteError( $name ) {
2591 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2594 public function showFileNotFoundError( $name ) {
2595 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2599 * Add a "return to" link pointing to a specified title
2601 * @param Title $title Title to link
2602 * @param array $query Query string parameters
2603 * @param string $text Text of the link (input is not escaped)
2604 * @param array $options Options array to pass to Linker
2606 public function addReturnTo( $title, array $query = array(), $text = null, $options = array() ) {
2607 $link = $this->msg( 'returnto' )->rawParams(
2608 Linker
::link( $title, $text, array(), $query, $options ) )->escaped();
2609 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2613 * Add a "return to" link pointing to a specified title,
2614 * or the title indicated in the request, or else the main page
2616 * @param mixed $unused
2617 * @param Title|string $returnto Title or String to return to
2618 * @param string $returntoquery Query string for the return to link
2620 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2621 if ( $returnto == null ) {
2622 $returnto = $this->getRequest()->getText( 'returnto' );
2625 if ( $returntoquery == null ) {
2626 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2629 if ( $returnto === '' ) {
2630 $returnto = Title
::newMainPage();
2633 if ( is_object( $returnto ) ) {
2634 $titleObj = $returnto;
2636 $titleObj = Title
::newFromText( $returnto );
2638 if ( !is_object( $titleObj ) ) {
2639 $titleObj = Title
::newMainPage();
2642 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2646 * @param Skin $sk The given Skin
2647 * @param bool $includeStyle Unused
2648 * @return string The doctype, opening "<html>", and head element.
2650 public function headElement( Skin
$sk, $includeStyle = true ) {
2653 $userdir = $this->getLanguage()->getDir();
2654 $sitedir = $wgContLang->getDir();
2656 $ret = Html
::htmlHeader( $sk->getHtmlElementAttributes() );
2658 if ( $this->getHTMLTitle() == '' ) {
2659 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2662 $openHead = Html
::openElement( 'head' );
2664 # Don't bother with the newline if $head == ''
2665 $ret .= "$openHead\n";
2668 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2669 // Add <meta charset="UTF-8">
2670 // This should be before <title> since it defines the charset used by
2671 // text including the text inside <title>.
2672 // The spec recommends defining XHTML5's charset using the XML declaration
2674 // Our XML declaration is output by Html::htmlHeader.
2675 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2676 // http://www.whatwg.org/html/semantics.html#charset
2677 $ret .= Html
::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2680 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2682 foreach ( $this->getHeadLinksArray() as $item ) {
2683 $ret .= $item . "\n";
2686 // No newline after buildCssLinks since makeResourceLoaderLink did that already
2687 $ret .= $this->buildCssLinks();
2689 $ret .= $this->getHeadScripts() . "\n";
2691 foreach ( $this->mHeadItems
as $item ) {
2692 $ret .= $item . "\n";
2695 $closeHead = Html
::closeElement( 'head' );
2697 $ret .= "$closeHead\n";
2700 $bodyClasses = array();
2701 $bodyClasses[] = 'mediawiki';
2703 # Classes for LTR/RTL directionality support
2704 $bodyClasses[] = $userdir;
2705 $bodyClasses[] = "sitedir-$sitedir";
2707 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2708 # A <body> class is probably not the best way to do this . . .
2709 $bodyClasses[] = 'capitalize-all-nouns';
2712 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2713 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2715 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2717 $bodyAttrs = array();
2718 // While the implode() is not strictly needed, it's used for backwards compatibility
2719 // (this used to be built as a string and hooks likely still expect that).
2720 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2722 // Allow skins and extensions to add body attributes they need
2723 $sk->addToBodyAttributes( $this, $bodyAttrs );
2724 Hooks
::run( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2726 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2732 * Get a ResourceLoader object associated with this OutputPage
2734 * @return ResourceLoader
2736 public function getResourceLoader() {
2737 if ( is_null( $this->mResourceLoader
) ) {
2738 $this->mResourceLoader
= new ResourceLoader(
2740 LoggerFactory
::getInstance( 'resourceloader' )
2743 return $this->mResourceLoader
;
2748 * @param array|string $modules One or more module names
2749 * @param string $only ResourceLoaderModule TYPE_ class constant
2750 * @param bool $useESI
2751 * @param array $extraQuery Array with extra query parameters to add to each
2752 * request. array( param => value ).
2753 * @param bool $loadCall If true, output an (asynchronous) mw.loader.load()
2754 * call rather than a "<script src='...'>" tag.
2755 * @return string The html "<script>", "<link>" and "<style>" tags
2757 public function makeResourceLoaderLink( $modules, $only, $useESI = false,
2758 array $extraQuery = array(), $loadCall = false
2760 $modules = (array)$modules;
2764 'states' => array(),
2767 if ( !count( $modules ) ) {
2771 if ( count( $modules ) > 1 ) {
2772 // Remove duplicate module requests
2773 $modules = array_unique( $modules );
2774 // Sort module names so requests are more uniform
2777 if ( ResourceLoader
::inDebugMode() ) {
2778 // Recursively call us for every item
2779 foreach ( $modules as $name ) {
2780 $link = $this->makeResourceLoaderLink( $name, $only, $useESI );
2781 $links['html'] .= $link['html'];
2782 $links['states'] +
= $link['states'];
2788 if ( !is_null( $this->mTarget
) ) {
2789 $extraQuery['target'] = $this->mTarget
;
2792 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2793 $sortedModules = array();
2794 $resourceLoader = $this->getResourceLoader();
2795 $resourceLoaderUseESI = $this->getConfig()->get( 'ResourceLoaderUseESI' );
2796 foreach ( $modules as $name ) {
2797 $module = $resourceLoader->getModule( $name );
2798 # Check that we're allowed to include this module on this page
2800 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2801 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2802 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2803 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2804 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2805 && $only == ResourceLoaderModule
::TYPE_COMBINED
)
2806 ||
( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) )
2811 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2814 foreach ( $sortedModules as $source => $groups ) {
2815 foreach ( $groups as $group => $grpModules ) {
2816 // Special handling for user-specific groups
2818 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2819 $user = $this->getUser()->getName();
2822 // Create a fake request based on the one we are about to make so modules return
2823 // correct timestamp and emptiness data
2824 $query = ResourceLoader
::makeLoaderQuery(
2825 array(), // modules; not determined yet
2826 $this->getLanguage()->getCode(),
2827 $this->getSkin()->getSkinName(),
2829 null, // version; not determined yet
2830 ResourceLoader
::inDebugMode(),
2831 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2832 $this->isPrintable(),
2833 $this->getRequest()->getBool( 'handheld' ),
2836 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2838 // Extract modules that know they're empty and see if we have one or more
2841 foreach ( $grpModules as $key => $module ) {
2842 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2843 // If we're only getting the styles, we don't need to do anything for empty modules.
2844 if ( $module->isKnownEmpty( $context ) ) {
2845 unset( $grpModules[$key] );
2846 if ( $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2847 $links['states'][$key] = 'ready';
2851 $isRaw |
= $module->isRaw();
2854 // If there are no non-empty modules, skip this group
2855 if ( count( $grpModules ) === 0 ) {
2859 // Inline private modules. These can't be loaded through load.php for security
2860 // reasons, see bug 34907. Note that these modules should be loaded from
2861 // getHeadScripts() before the first loader call. Otherwise other modules can't
2862 // properly use them as dependencies (bug 30914)
2863 if ( $group === 'private' ) {
2864 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2865 $links['html'] .= Html
::inlineStyle(
2866 $resourceLoader->makeModuleResponse( $context, $grpModules )
2869 $links['html'] .= ResourceLoader
::makeInlineScript(
2870 $resourceLoader->makeModuleResponse( $context, $grpModules )
2873 $links['html'] .= "\n";
2877 // Special handling for the user group; because users might change their stuff
2878 // on-wiki like user pages, or user preferences; we need to find the highest
2879 // timestamp of these user-changeable modules so we can ensure cache misses on change
2880 // This should NOT be done for the site group (bug 27564) because anons get that too
2881 // and we shouldn't be putting timestamps in Squid-cached HTML
2883 if ( $group === 'user' ) {
2884 $query['version'] = $resourceLoader->getCombinedVersion( $context, array_keys( $grpModules ) );
2887 $query['modules'] = ResourceLoader
::makePackedModulesString( array_keys( $grpModules ) );
2888 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2889 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2891 if ( $useESI && $resourceLoaderUseESI ) {
2892 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2893 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2894 $link = Html
::inlineStyle( $esi );
2896 $link = Html
::inlineScript( $esi );
2899 // Automatically select style/script elements
2900 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2901 $link = Html
::linkedStyle( $url );
2902 } elseif ( $loadCall ) {
2903 $link = ResourceLoader
::makeInlineScript(
2904 Xml
::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2907 $link = Html
::linkedScript( $url );
2908 if ( !$context->getRaw() && !$isRaw ) {
2909 // Wrap only=script / only=combined requests in a conditional as
2910 // browsers not supported by the startup module would unconditionally
2911 // execute this module. Otherwise users will get "ReferenceError: mw is
2912 // undefined" or "jQuery is undefined" from e.g. a "site" module.
2913 $link = ResourceLoader
::makeInlineScript(
2914 Xml
::encodeJsCall( 'document.write', array( $link ) )
2918 // For modules requested directly in the html via <link> or <script>,
2919 // tell mw.loader they are being loading to prevent duplicate requests.
2920 foreach ( $grpModules as $key => $module ) {
2921 // Don't output state=loading for the startup module..
2922 if ( $key !== 'startup' ) {
2923 $links['states'][$key] = 'loading';
2929 if ( $group == 'noscript' ) {
2930 $links['html'] .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2932 $links['html'] .= $link . "\n";
2941 * Build html output from an array of links from makeResourceLoaderLink.
2942 * @param array $links
2943 * @return string HTML
2945 protected static function getHtmlFromLoaderLinks( array $links ) {
2948 foreach ( $links as $link ) {
2949 if ( !is_array( $link ) ) {
2952 $html .= $link['html'];
2953 $states +
= $link['states'];
2957 if ( count( $states ) ) {
2958 $html = ResourceLoader
::makeInlineScript(
2959 ResourceLoader
::makeLoaderStateScript( $states )
2967 * JS stuff to put in the "<head>". This is the startup module, config
2968 * vars and modules marked with position 'top'
2970 * @return string HTML fragment
2972 function getHeadScripts() {
2973 // Startup - this will immediately load jquery and mediawiki modules
2975 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2977 // Load config before anything else
2978 $links[] = ResourceLoader
::makeInlineScript(
2979 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2982 // Load embeddable private modules before any loader links
2983 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2984 // in mw.loader.implement() calls and deferred until mw.user is available
2985 $embedScripts = array( 'user.options' );
2986 $links[] = $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2987 // Separate user.tokens as otherwise caching will be allowed (T84960)
2988 $links[] = $this->makeResourceLoaderLink( 'user.tokens', ResourceLoaderModule
::TYPE_COMBINED
);
2990 // Scripts and messages "only" requests marked for top inclusion
2991 $links[] = $this->makeResourceLoaderLink(
2992 $this->getModuleScripts( true, 'top' ),
2993 ResourceLoaderModule
::TYPE_SCRIPTS
2996 // Modules requests - let the client calculate dependencies and batch requests as it likes
2997 // Only load modules that have marked themselves for loading at the top
2998 $modules = $this->getModules( true, 'top' );
3000 $links[] = ResourceLoader
::makeInlineScript(
3001 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
3005 if ( $this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
3006 $links[] = $this->getScriptsForBottomQueue( true );
3009 return self
::getHtmlFromLoaderLinks( $links );
3013 * JS stuff to put at the 'bottom', which can either be the bottom of the
3014 * "<body>" or the bottom of the "<head>" depending on
3015 * $wgResourceLoaderExperimentalAsyncLoading: modules marked with position
3016 * 'bottom', legacy scripts ($this->mScripts), user preferences, site JS
3019 * @param bool $inHead If true, this HTML goes into the "<head>",
3020 * if false it goes into the "<body>".
3023 function getScriptsForBottomQueue( $inHead ) {
3024 // Scripts "only" requests marked for bottom inclusion
3025 // If we're in the <head>, use load() calls rather than <script src="..."> tags
3028 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
3029 ResourceLoaderModule
::TYPE_SCRIPTS
, /* $useESI = */ false, /* $extraQuery = */ array(),
3030 /* $loadCall = */ $inHead
3033 $links[] = $this->makeResourceLoaderLink( $this->getModuleStyles( true, 'bottom' ),
3034 ResourceLoaderModule
::TYPE_STYLES
, /* $useESI = */ false, /* $extraQuery = */ array(),
3035 /* $loadCall = */ $inHead
3038 // Modules requests - let the client calculate dependencies and batch requests as it likes
3039 // Only load modules that have marked themselves for loading at the bottom
3040 $modules = $this->getModules( true, 'bottom' );
3042 $links[] = ResourceLoader
::makeInlineScript(
3043 Xml
::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
3048 $links[] = "\n" . $this->mScripts
;
3050 // Add site JS if enabled
3051 $links[] = $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
,
3052 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3055 // Add user JS if enabled
3056 if ( $this->getConfig()->get( 'AllowUserJs' )
3057 && $this->getUser()->isLoggedIn()
3058 && $this->getTitle()
3059 && $this->getTitle()->isJsSubpage()
3060 && $this->userCanPreview()
3062 # XXX: additional security check/prompt?
3063 // We're on a preview of a JS subpage
3064 // Exclude this page from the user module in case it's in there (bug 26283)
3065 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
3066 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
3068 // Load the previewed JS
3069 $links[] = Html
::inlineScript( "\n"
3070 . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
3072 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3073 // asynchronously and may arrive *after* the inline script here. So the previewed code
3074 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
3076 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3077 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
,
3078 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3082 // Group JS is only enabled if site JS is enabled.
3083 $links[] = $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule
::TYPE_COMBINED
,
3084 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3087 return self
::getHtmlFromLoaderLinks( $links );
3091 * JS stuff to put at the bottom of the "<body>"
3094 function getBottomScripts() {
3095 // In case the skin wants to add bottom CSS
3096 $this->getSkin()->setupSkinUserCss( $this );
3098 // Optimise jQuery ready event cross-browser.
3099 // This also enforces $.isReady to be true at </body> which fixes the
3100 // mw.loader bug in Firefox with using document.write between </body>
3101 // and the DOMContentReady event (bug 47457).
3102 $html = Html
::inlineScript( 'if(window.jQuery)jQuery.ready();' );
3104 if ( !$this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
3105 $html .= $this->getScriptsForBottomQueue( false );
3112 * Get the javascript config vars to include on this page
3114 * @return array Array of javascript config vars
3117 public function getJsConfigVars() {
3118 return $this->mJsConfigVars
;
3122 * Add one or more variables to be set in mw.config in JavaScript
3124 * @param string|array $keys Key or array of key/value pairs
3125 * @param mixed $value [optional] Value of the configuration variable
3127 public function addJsConfigVars( $keys, $value = null ) {
3128 if ( is_array( $keys ) ) {
3129 foreach ( $keys as $key => $value ) {
3130 $this->mJsConfigVars
[$key] = $value;
3135 $this->mJsConfigVars
[$keys] = $value;
3139 * Get an array containing the variables to be set in mw.config in JavaScript.
3141 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3142 * - in other words, page-independent/site-wide variables (without state).
3143 * You will only be adding bloat to the html page and causing page caches to
3144 * have to be purged on configuration changes.
3147 public function getJSVars() {
3152 $canonicalSpecialPageName = false; # bug 21115
3154 $title = $this->getTitle();
3155 $ns = $title->getNamespace();
3156 $canonicalNamespace = MWNamespace
::exists( $ns )
3157 ? MWNamespace
::getCanonicalName( $ns )
3158 : $title->getNsText();
3160 $sk = $this->getSkin();
3161 // Get the relevant title so that AJAX features can use the correct page name
3162 // when making API requests from certain special pages (bug 34972).
3163 $relevantTitle = $sk->getRelevantTitle();
3164 $relevantUser = $sk->getRelevantUser();
3166 if ( $ns == NS_SPECIAL
) {
3167 list( $canonicalSpecialPageName, /*...*/ ) =
3168 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3169 } elseif ( $this->canUseWikiPage() ) {
3170 $wikiPage = $this->getWikiPage();
3171 $curRevisionId = $wikiPage->getLatest();
3172 $articleId = $wikiPage->getId();
3175 $lang = $title->getPageLanguage();
3177 // Pre-process information
3178 $separatorTransTable = $lang->separatorTransformTable();
3179 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
3180 $compactSeparatorTransTable = array(
3181 implode( "\t", array_keys( $separatorTransTable ) ),
3182 implode( "\t", $separatorTransTable ),
3184 $digitTransTable = $lang->digitTransformTable();
3185 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
3186 $compactDigitTransTable = array(
3187 implode( "\t", array_keys( $digitTransTable ) ),
3188 implode( "\t", $digitTransTable ),
3191 $user = $this->getUser();
3194 'wgCanonicalNamespace' => $canonicalNamespace,
3195 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3196 'wgNamespaceNumber' => $title->getNamespace(),
3197 'wgPageName' => $title->getPrefixedDBkey(),
3198 'wgTitle' => $title->getText(),
3199 'wgCurRevisionId' => $curRevisionId,
3200 'wgRevisionId' => (int)$this->getRevisionId(),
3201 'wgArticleId' => $articleId,
3202 'wgIsArticle' => $this->isArticle(),
3203 'wgIsRedirect' => $title->isRedirect(),
3204 'wgAction' => Action
::getActionName( $this->getContext() ),
3205 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3206 'wgUserGroups' => $user->getEffectiveGroups(),
3207 'wgCategories' => $this->getCategories(),
3208 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3209 'wgPageContentLanguage' => $lang->getCode(),
3210 'wgPageContentModel' => $title->getContentModel(),
3211 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3212 'wgDigitTransformTable' => $compactDigitTransTable,
3213 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3214 'wgMonthNames' => $lang->getMonthNamesArray(),
3215 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3216 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3217 'wgRelevantArticleId' => $relevantTitle->getArticleId(),
3220 if ( $user->isLoggedIn() ) {
3221 $vars['wgUserId'] = $user->getId();
3222 $vars['wgUserEditCount'] = $user->getEditCount();
3223 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3224 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3225 // Get the revision ID of the oldest new message on the user's talk
3226 // page. This can be used for constructing new message alerts on
3228 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3231 if ( $wgContLang->hasVariants() ) {
3232 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3234 // Same test as SkinTemplate
3235 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3236 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3238 foreach ( $title->getRestrictionTypes() as $type ) {
3239 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3242 if ( $title->isMainPage() ) {
3243 $vars['wgIsMainPage'] = true;
3246 if ( $this->mRedirectedFrom
) {
3247 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3250 if ( $relevantUser ) {
3251 $vars['wgRelevantUserName'] = $relevantUser->getName();
3254 // Allow extensions to add their custom variables to the mw.config map.
3255 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3256 // page-dependant but site-wide (without state).
3257 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3258 Hooks
::run( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3260 // Merge in variables from addJsConfigVars last
3261 return array_merge( $vars, $this->getJsConfigVars() );
3265 * To make it harder for someone to slip a user a fake
3266 * user-JavaScript or user-CSS preview, a random token
3267 * is associated with the login session. If it's not
3268 * passed back with the preview request, we won't render
3273 public function userCanPreview() {
3274 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3275 ||
!$this->getRequest()->wasPosted()
3276 ||
!$this->getUser()->matchEditToken(
3277 $this->getRequest()->getVal( 'wpEditToken' ) )
3281 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3284 if ( !$this->getTitle()->isSubpageOf( $this->getUser()->getUserPage() ) ) {
3285 // Don't execute another user's CSS or JS on preview (T85855)
3289 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3293 * @return array Array in format "link name or number => 'link html'".
3295 public function getHeadLinksArray() {
3299 $config = $this->getConfig();
3301 $canonicalUrl = $this->mCanonicalUrl
;
3303 $tags['meta-generator'] = Html
::element( 'meta', array(
3304 'name' => 'generator',
3305 'content' => "MediaWiki $wgVersion",
3308 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3309 $tags['meta-referrer'] = Html
::element( 'meta', array(
3310 'name' => 'referrer',
3311 'content' => $config->get( 'ReferrerPolicy' )
3315 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3316 if ( $p !== 'index,follow' ) {
3317 // http://www.robotstxt.org/wc/meta-user.html
3318 // Only show if it's different from the default robots policy
3319 $tags['meta-robots'] = Html
::element( 'meta', array(
3325 foreach ( $this->mMetatags
as $tag ) {
3326 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3328 $tag[0] = substr( $tag[0], 5 );
3332 $tagName = "meta-{$tag[0]}";
3333 if ( isset( $tags[$tagName] ) ) {
3334 $tagName .= $tag[1];
3336 $tags[$tagName] = Html
::element( 'meta',
3339 'content' => $tag[1]
3344 foreach ( $this->mLinktags
as $tag ) {
3345 $tags[] = Html
::element( 'link', $tag );
3348 # Universal edit button
3349 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3350 $user = $this->getUser();
3351 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3352 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3353 // Original UniversalEditButton
3354 $msg = $this->msg( 'edit' )->text();
3355 $tags['universal-edit-button'] = Html
::element( 'link', array(
3356 'rel' => 'alternate',
3357 'type' => 'application/x-wiki',
3359 'href' => $this->getTitle()->getEditURL(),
3361 // Alternate edit link
3362 $tags['alternative-edit'] = Html
::element( 'link', array(
3365 'href' => $this->getTitle()->getEditURL(),
3370 # Generally the order of the favicon and apple-touch-icon links
3371 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3372 # uses whichever one appears later in the HTML source. Make sure
3373 # apple-touch-icon is specified first to avoid this.
3374 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3375 $tags['apple-touch-icon'] = Html
::element( 'link', array(
3376 'rel' => 'apple-touch-icon',
3377 'href' => $config->get( 'AppleTouchIcon' )
3381 if ( $config->get( 'Favicon' ) !== false ) {
3382 $tags['favicon'] = Html
::element( 'link', array(
3383 'rel' => 'shortcut icon',
3384 'href' => $config->get( 'Favicon' )
3388 # OpenSearch description link
3389 $tags['opensearch'] = Html
::element( 'link', array(
3391 'type' => 'application/opensearchdescription+xml',
3392 'href' => wfScript( 'opensearch_desc' ),
3393 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3396 if ( $config->get( 'EnableAPI' ) ) {
3397 # Real Simple Discovery link, provides auto-discovery information
3398 # for the MediaWiki API (and potentially additional custom API
3399 # support such as WordPress or Twitter-compatible APIs for a
3400 # blogging extension, etc)
3401 $tags['rsd'] = Html
::element( 'link', array(
3403 'type' => 'application/rsd+xml',
3404 // Output a protocol-relative URL here if $wgServer is protocol-relative
3405 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3406 'href' => wfExpandUrl( wfAppendQuery(
3408 array( 'action' => 'rsd' ) ),
3415 if ( !$config->get( 'DisableLangConversion' ) ) {
3416 $lang = $this->getTitle()->getPageLanguage();
3417 if ( $lang->hasVariants() ) {
3418 $variants = $lang->getVariants();
3419 foreach ( $variants as $_v ) {
3420 $tags["variant-$_v"] = Html
::element( 'link', array(
3421 'rel' => 'alternate',
3422 'hreflang' => wfBCP47( $_v ),
3423 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3427 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3428 $tags["variant-x-default"] = Html
::element( 'link', array(
3429 'rel' => 'alternate',
3430 'hreflang' => 'x-default',
3431 'href' => $this->getTitle()->getLocalURL() ) );
3436 if ( $config->get( 'RightsPage' ) ) {
3437 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3440 $copyright = $copy->getLocalURL();
3444 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3445 $copyright = $config->get( 'RightsUrl' );
3449 $tags['copyright'] = Html
::element( 'link', array(
3450 'rel' => 'copyright',
3451 'href' => $copyright )
3456 if ( $config->get( 'Feed' ) ) {
3457 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3458 # Use the page name for the title. In principle, this could
3459 # lead to issues with having the same name for different feeds
3460 # corresponding to the same page, but we can't avoid that at
3463 $tags[] = $this->feedLink(
3466 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3467 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3471 # Recent changes feed should appear on every page (except recentchanges,
3472 # that would be redundant). Put it after the per-page feed to avoid
3473 # changing existing behavior. It's still available, probably via a
3474 # menu in your browser. Some sites might have a different feed they'd
3475 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3476 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3477 # If so, use it instead.
3478 $sitename = $config->get( 'Sitename' );
3479 if ( $config->get( 'OverrideSiteFeed' ) ) {
3480 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3481 // Note, this->feedLink escapes the url.
3482 $tags[] = $this->feedLink(
3485 $this->msg( "site-{$type}-feed", $sitename )->text()
3488 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3489 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3490 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3491 $tags[] = $this->feedLink(
3493 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3494 # For grep: 'site-rss-feed', 'site-atom-feed'
3495 $this->msg( "site-{$format}-feed", $sitename )->text()
3502 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3503 if ( $canonicalUrl !== false ) {
3504 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3506 $reqUrl = $this->getRequest()->getRequestURL();
3507 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3510 if ( $canonicalUrl !== false ) {
3511 $tags[] = Html
::element( 'link', array(
3512 'rel' => 'canonical',
3513 'href' => $canonicalUrl
3521 * @return string HTML tag links to be put in the header.
3522 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3523 * OutputPage::getHeadLinksArray directly.
3525 public function getHeadLinks() {
3526 wfDeprecated( __METHOD__
, '1.24' );
3527 return implode( "\n", $this->getHeadLinksArray() );
3531 * Generate a "<link rel/>" for a feed.
3533 * @param string $type Feed type
3534 * @param string $url URL to the feed
3535 * @param string $text Value of the "title" attribute
3536 * @return string HTML fragment
3538 private function feedLink( $type, $url, $text ) {
3539 return Html
::element( 'link', array(
3540 'rel' => 'alternate',
3541 'type' => "application/$type+xml",
3548 * Add a local or specified stylesheet, with the given media options.
3549 * Meant primarily for internal use...
3551 * @param string $style URL to the file
3552 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3553 * @param string $condition For IE conditional comments, specifying an IE version
3554 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3556 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3558 // Even though we expect the media type to be lowercase, but here we
3559 // force it to lowercase to be safe.
3561 $options['media'] = $media;
3564 $options['condition'] = $condition;
3567 $options['dir'] = $dir;
3569 $this->styles
[$style] = $options;
3573 * Adds inline CSS styles
3574 * @param mixed $style_css Inline CSS
3575 * @param string $flip Set to 'flip' to flip the CSS if needed
3577 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3578 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3579 # If wanted, and the interface is right-to-left, flip the CSS
3580 $style_css = CSSJanus
::transform( $style_css, true, false );
3582 $this->mInlineStyles
.= Html
::inlineStyle( $style_css ) . "\n";
3586 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3587 * These will be applied to various media & IE conditionals.
3591 public function buildCssLinks() {
3594 $this->getSkin()->setupSkinUserCss( $this );
3596 // Add ResourceLoader styles
3597 // Split the styles into these groups
3602 'private' => array(),
3603 'noscript' => array()
3606 $otherTags = ''; // Tags to append after the normal <link> tags
3607 $resourceLoader = $this->getResourceLoader();
3609 $moduleStyles = $this->getModuleStyles( true, 'top' );
3611 // Per-site custom styles
3612 $moduleStyles[] = 'site';
3613 $moduleStyles[] = 'noscript';
3614 $moduleStyles[] = 'user.groups';
3616 // Per-user custom styles
3617 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3618 && $this->userCanPreview()
3620 // We're on a preview of a CSS subpage
3621 // Exclude this page from the user module in case it's in there (bug 26283)
3622 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3623 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3625 $otherTags .= $link['html'];
3627 // Load the previewed CSS
3628 // If needed, Janus it first. This is user-supplied CSS, so it's
3629 // assumed to be right for the content language directionality.
3630 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3631 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3632 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3634 $otherTags .= Html
::inlineStyle( $previewedCSS ) . "\n";
3636 // Load the user styles normally
3637 $moduleStyles[] = 'user';
3640 // Per-user preference styles
3641 $moduleStyles[] = 'user.cssprefs';
3643 foreach ( $moduleStyles as $name ) {
3644 $module = $resourceLoader->getModule( $name );
3648 $group = $module->getGroup();
3649 // Modules in groups different than the ones listed on top (see $styles assignment)
3650 // will be placed in the "other" group
3651 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3654 // We want site, private and user styles to override dynamically added
3655 // styles from modules, but we want dynamically added styles to override
3656 // statically added styles from other modules. So the order has to be
3657 // other, dynamic, site, private, user. Add statically added styles for
3659 $links[] = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3660 // Add normal styles added through addStyle()/addInlineStyle() here
3661 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3662 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3663 // We use a <meta> tag with a made-up name for this because that's valid HTML
3664 $links[] = Html
::element(
3666 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3669 // Add site, private and user styles
3670 // 'private' at present only contains user.options, so put that before 'user'
3671 // Any future private modules will likely have a similar user-specific character
3672 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3673 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3674 ResourceLoaderModule
::TYPE_STYLES
3678 // Add stuff in $otherTags (previewed user CSS if applicable)
3679 return self
::getHtmlFromLoaderLinks( $links ) . $otherTags;
3685 public function buildCssLinksArray() {
3688 // Add any extension CSS
3689 foreach ( $this->mExtStyles
as $url ) {
3690 $this->addStyle( $url );
3692 $this->mExtStyles
= array();
3694 foreach ( $this->styles
as $file => $options ) {
3695 $link = $this->styleLink( $file, $options );
3697 $links[$file] = $link;
3704 * Generate \<link\> tags for stylesheets
3706 * @param string $style URL to the file
3707 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3708 * @return string HTML fragment
3710 protected function styleLink( $style, array $options ) {
3711 if ( isset( $options['dir'] ) ) {
3712 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3717 if ( isset( $options['media'] ) ) {
3718 $media = self
::transformCssMedia( $options['media'] );
3719 if ( is_null( $media ) ) {
3726 if ( substr( $style, 0, 1 ) == '/' ||
3727 substr( $style, 0, 5 ) == 'http:' ||
3728 substr( $style, 0, 6 ) == 'https:' ) {
3731 $config = $this->getConfig();
3732 $url = $config->get( 'StylePath' ) . '/' . $style . '?' . $config->get( 'StyleVersion' );
3735 $link = Html
::linkedStyle( $url, $media );
3737 if ( isset( $options['condition'] ) ) {
3738 $condition = htmlspecialchars( $options['condition'] );
3739 $link = "<!--[if $condition]>$link<![endif]-->";
3745 * Transform "media" attribute based on request parameters
3747 * @param string $media Current value of the "media" attribute
3748 * @return string Modified value of the "media" attribute, or null to skip
3751 public static function transformCssMedia( $media ) {
3754 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3755 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3757 // Switch in on-screen display for media testing
3759 'printable' => 'print',
3760 'handheld' => 'handheld',
3762 foreach ( $switches as $switch => $targetMedia ) {
3763 if ( $wgRequest->getBool( $switch ) ) {
3764 if ( $media == $targetMedia ) {
3766 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3767 // This regex will not attempt to understand a comma-separated media_query_list
3769 // Example supported values for $media:
3770 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3771 // Example NOT supported value for $media:
3772 // '3d-glasses, screen, print and resolution > 90dpi'
3774 // If it's a print request, we never want any kind of screen stylesheets
3775 // If it's a handheld request (currently the only other choice with a switch),
3776 // we don't want simple 'screen' but we might want screen queries that
3777 // have a max-width or something, so we'll pass all others on and let the
3778 // client do the query.
3779 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3790 * Add a wikitext-formatted message to the output.
3791 * This is equivalent to:
3793 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3795 public function addWikiMsg( /*...*/ ) {
3796 $args = func_get_args();
3797 $name = array_shift( $args );
3798 $this->addWikiMsgArray( $name, $args );
3802 * Add a wikitext-formatted message to the output.
3803 * Like addWikiMsg() except the parameters are taken as an array
3804 * instead of a variable argument list.
3806 * @param string $name
3807 * @param array $args
3809 public function addWikiMsgArray( $name, $args ) {
3810 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3814 * This function takes a number of message/argument specifications, wraps them in
3815 * some overall structure, and then parses the result and adds it to the output.
3817 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3818 * and so on. The subsequent arguments may be either
3819 * 1) strings, in which case they are message names, or
3820 * 2) arrays, in which case, within each array, the first element is the message
3821 * name, and subsequent elements are the parameters to that message.
3823 * Don't use this for messages that are not in the user's interface language.
3827 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3831 * $wgOut->addWikiText( "<div class='error'>\n"
3832 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3834 * The newline after the opening div is needed in some wikitext. See bug 19226.
3836 * @param string $wrap
3838 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3839 $msgSpecs = func_get_args();
3840 array_shift( $msgSpecs );
3841 $msgSpecs = array_values( $msgSpecs );
3843 foreach ( $msgSpecs as $n => $spec ) {
3844 if ( is_array( $spec ) ) {
3846 $name = array_shift( $args );
3847 if ( isset( $args['options'] ) ) {
3848 unset( $args['options'] );
3850 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3858 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3860 $this->addWikiText( $s );
3864 * Include jQuery core. Use this to avoid loading it multiple times
3865 * before we get a usable script loader.
3867 * @param array $modules List of jQuery modules which should be loaded
3868 * @return array The list of modules which were not loaded.
3870 * @deprecated since 1.17
3872 public function includeJQuery( array $modules = array() ) {
3877 * Enables/disables TOC, doesn't override __NOTOC__
3881 public function enableTOC( $flag = true ) {
3882 $this->mEnableTOC
= $flag;
3889 public function isTOCEnabled() {
3890 return $this->mEnableTOC
;
3894 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3898 public function enableSectionEditLinks( $flag = true ) {
3899 $this->mEnableSectionEditLinks
= $flag;
3906 public function sectionEditLinksEnabled() {
3907 return $this->mEnableSectionEditLinks
;
3911 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3912 * MediaWiki and this OutputPage instance.
3916 public function enableOOUI() {
3917 OOUI\Theme
::setSingleton( new OOUI\
MediaWikiTheme() );
3918 OOUI\Element
::setDefaultDir( $this->getLanguage()->getDir() );
3919 $this->addModuleStyles( array(
3921 'oojs-ui.styles.icons',
3922 'oojs-ui.styles.indicators',
3923 'oojs-ui.styles.textures',